const app = getApp();
const url = app.globalData.url;
const WxParse = require('../../wxParse/wxParse.js');  
Page({

  /** 
   * 页面的初始数据
   */
  data: {
      qdday:0,
      sysW: null,
      qds:true,
      qdcgs:false,
      qdrs:0,
      loding:true,
      lastDay: null,
      firstDay: null,
      year: null,
      hasEmptyGrid: false,
      cur_year: '',
      cur_month: '',
      firstDay: null,
      getDate:null,
      month:null,
      display:"none",
      week:[
          {
              wook: "一"
          }, {
              wook: "二"
          }, {
              wook: "三"
          }, {
              wook: "四"
          }, {
              wook: "五"
          }, {
              wook: "六"
          }, {
              wook: "日"
          },
      ],
      day:[
          {
              wook: '',
              src:"/img/ico/yqd.png",
          }, {
              wook: ''
          }, {
              wook: ''
          }, {
              wook: ''
          }, {
              wook: ''
          }, {
              wook: ''
          },{
              wook: ''
          }
      ],
      days:[
          {
             // src:"/img/ico/yqd.png"
          }
      ]
  },
   getProWeekList:function(){
       let that=this
       let date=new Date()
       let dateTime = date.getTime(); // 获取现在的时间
       let dateDay = date.getDay();// 获取现在的
       let oneDayTime = 24 * 60 * 60 * 1000; //一天的时间
       let proWeekList;
       let weekday;
       //  console.log(dateTime)
       for (let i = 0; i < 7; i++) {
          let time = dateTime - (dateDay - 1 - i) * oneDayTime;
          proWeekList = new Date(time).getDate(); //date格式转换为yyyy-mm-dd格式的字符串
          weekday = "day[" + i+"].wook"
          that.setData({
              [weekday]: proWeekList,
          })
          //that.data.day[i].wook = new Date(time).getDate();
      }
  },
  qdcgs(){
    this.setData({qdcgs:false});
  },
  dateSelectAction: function (e) {
      let cur_day = e.currentTarget.dataset.idx;
      let it = e.currentTarget.dataset.it;
      var tt='';
      if(it.item<this.data.getDate){
        if(!it.src){
          tt='补签未开启';
        }else{
          tt='已签到';
        }
        wx.showToast({
          title: tt,
          icon: 'none',
          duration: 2000
        })
      }else if(it.item==this.data.getDate){
        if(!it.src){
          this.qiandao();
        }else{
          tt='已签到';
          wx.showToast({
            title: tt,
            icon: 'none',
            duration: 2000
          })
        }
      }else{
        wx.showToast({
          title: "签到时间未到",
          icon: 'none',
          duration: 2000
        })
      }
      this.setData({
          todayIndex: cur_day
      })
      //  console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}日`);
  },

  setNowDate: function () {
      const date = new Date();
      const cur_year = date.getFullYear();
      const cur_month = date.getMonth() + 1;
      const todayIndex = date.getDate();
      //  console.log(`日期：${todayIndex}`)
      const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
      this.calculateEmptyGrids(cur_year, cur_month);
      this.calculateDays(cur_year, cur_month);
      this.setData({
          cur_year: cur_year,
          cur_month: cur_month,
          weeks_ch,
          todayIndex,
      })
  },

  getThisMonthDays(year, month) {
      return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
      return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
      const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
      let empytGrids = [];
      if (firstDayOfWeek > 0) {
          for (let i = 0; i < firstDayOfWeek; i++) {
              empytGrids.push(i);
          }
          this.setData({
              hasEmptyGrid: true,
              empytGrids
          });
      } else {
          this.setData({
              hasEmptyGrid: false,
              empytGrids: []
          });
      }
  },
  calculateDays(year, month) {
      let days = [];
      let weekday,src;
      const thisMonthDays = this.getThisMonthDays(year, month);

      for (let i = 1; i <= thisMonthDays; i++) {
          // days[i].push(i);
          weekday = "days[" + (i - 1) + "].item"
          
          //  console.log(weekday)
         this.setData({
             [weekday]:i,
             src:''
         })
      }
     
      //  console.log(this.data.days)
  },
  handleCalendar(e) {
      const handle = e.currentTarget.dataset.handle;
      const cur_year = this.data.cur_year;
      const cur_month = this.data.cur_month;
　　

        this.setData({
           days:[]
        })


      if (handle === 'prev') {
          let newMonth = cur_month - 1;
          let newYear = cur_year;
          if (newMonth < 1) {
              newYear = cur_year - 1;
              newMonth = 12;
          }

          this.calculateDays(newYear, newMonth);
          this.calculateEmptyGrids(newYear, newMonth);

          let firstDay = new Date(newYear, newMonth - 1, 1);
          this.data.firstDay = firstDay.getDay();
          this.setData({
              cur_year: newYear,
              cur_month: newMonth,
              marLet: this.data.firstDay
          })
          if (this.data.month == newMonth) {
              this.setData({
                  judge: 1
              })
          } else {
              this.setData({
                  judge: 0
              })
          }
      } else {
          let newMonth = cur_month + 1;
          let newYear = cur_year;
          if (newMonth > 12) {
              newYear = cur_year + 1;
              newMonth = 1;
          }

          this.calculateDays(newYear, newMonth);
          this.calculateEmptyGrids(newYear, newMonth);
          let firstDay = new Date(newYear, newMonth - 1, 1);
          this.data.firstDay = firstDay.getDay();
          this.setData({
              cur_year: newYear,
              cur_month: newMonth,
              marLet: this.data.firstDay
          })
          if (this.data.month == newMonth){
              this.setData({
                  judge:1
              })
          }else{
              this.setData({
                  judge: 0
              })
          }
      }
      this.getdyqd();
  },
  dataTime: function () {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth();
      var months = date.getMonth() + 1;

      //获取现今年份
      this.data.year = year;

      //获取现今月份
      this.data.month = months;

      //获取今日日期
      this.data.getDate = date.getDate();

      //最后一天是几号
      var d = new Date(year, months, 0);
      this.data.lastDay = d.getDate();

      //第一天星期几
      let firstDay = new Date(year, month, 1);
      this.data.firstDay = firstDay.getDay();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      var that = this;
      this.setNowDate();
      this.getProWeekList()

      this.dataTime();
      var res = wx.getSystemInfoSync();
      this.setData({
          sysW: (res.windowWidth-30) / 7,//更具屏幕宽度变化自动设置宽度
          marLet: this.data.firstDay,
          getDate: this.data.getDate,
          judge:1,
          month: this.data.month,
      });

      /**
       * 获取系统信息
       */
       console.log(res)
       console.log(this.data.sysW)
       console.log(that.data.month)
      this. peizi();
  },
    // 配置文件
    peizi: function () {
      let that = this;
      app.fetch('api/wx/getpeizi', { dlx: 'xcxqd' }, "GET", (err, data) => {
        //  console.log(data)
        if (data.code == 200) {
          wx.setNavigationBarTitle({
            title: "签到"
          });
          data.data.xcxqd.qdtp.txt=url+data.data.xcxqd.qdtp.txt;
          // article_content: WxParse.wxParse('article', 'html', data.data.xcxyqyj.yqgz.txt, that, 0);
          that.setData({ peizi: data.data});
          that.hquser();
        } else {
          wx.showModal({
            title: '接口数据错误',
            content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
            showCancel: false,//是否显示取消按钮
            confirmText: "好的",//默认是“确定”
            confirmColor: 'skyblue',//确定文字的颜色
            success: function (res) {
  
            },
            fail: function (res) { },//接口调用失败的回调函数
            complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
          })
        }
      })
    },
    qiandao(){
      let that=this;
      let us=that.data.user,pz=that.data.peizi;
      let sj={
        uid:us.uid
      };
      app.fetch('api/wx/addqd', sj, "POST", (err, data) => {
        //  console.log(data)
        if (data.code == 200) {
          that.setData({qdrs:parseInt(data.qdrs)+1,qdcgs:true});
          that.getqdb();
          if (pz.xcxqd.qdjljb.txt > 0) {
            var tt = '于' + data.rq + "签到成功,获取" + pz.xcxqd.qdjljb.txt + "个" + pz.xcx.jb.txt;
            that.czjb(us.uid, 1, pz.xcxqd.qdjljb.txt, tt, '于' + data.rq + "签到成功,获取");
          }
        }
      })
    },
    czjb(uid,sz, jb, tt, xlx) {
      let that = this;
      let sj = {
        uid:uid,
        sz: sz,
        jb: jb,
        tt: tt,
        lx: 'xcx',
        xlx: xlx ? xlx : ''
      };
      app.fetch('api/wx/czjb', sj, "POST", (err, data) => {
        //  console.log(data)
        if (data.code == 200) {
          // that.hquser();
        }
      })
    },
    getqdb(){
      let that=this;
      let us=that.data.user,pz=that.data.peizi,it=that.data.days;
      let sj={
        uid:us.uid
      };
      app.fetch('api/wx/getqdb', sj, "POST", (err, data) => {
        //  console.log(data)
        if (data.code != 500) {
          for(var i=0;i<it.length;i++){
            for(var p of data.list){
              if(it[i].item==p.r){
                it[i].src="/img/ico/qdg.png";
              }
              // console.log(p);
            }
          }
            that.setData({
              qdday:data.y,
              qds:data.qd==0?true:false,
              days:it,
              loding: false 
            })
        }
      })
    },
    getdyqd(){
      let that=this;
      let us=that.data.user,pz=that.data.peizi,it=that.data.days;
      let sj={
        uid:us.uid,
        yy:that.data.cur_month,
        nn:that.data.cur_year,
      };
      app.fetch('api/wx/getqdb', sj, "POST", (err, data) => {
        //  console.log(data)
        if (data.code != 500) {
          for(var i=0;i<it.length;i++){
            for(var p of data.list){
              if(it[i].item==p.r){
                it[i].src="/img/ico/qdg.png";
              }
              // console.log(p);
            }
          }
            that.setData({
              days:it,
              qdday:data.y,
            })
        }
      })
    },
    // 获取user信息;
    hquser() {
      let that = this;
      wx.getStorage({
        key: 'openid',
        success(res) {
          app.fetch('api/wx/user', { openid: res.data,yq:'yq' }, "POST", (err, data) => {
            if (data.code == 200) {
              that.setData({ user: data.data[0] })
              // that.getcsData();
              that.getqdb();
            }else{
              wx.showModal({
                title: '提示',
                content: data.msg,
                success(res){
                  if (res.cancel) {
                    //点击取消,默认隐藏弹框
                    // if (options.finish) {
                      wx.navigateBack({ 
                        delta: 1,
                        fail(){
                          wx.redirectTo({
                            url: "/pages/my/my"
                          })
                        }
                       })
                    // }
                  } else {
                      wx.redirectTo({
                        url: "/pages/my/my"
                      })
                  }
                }
              })
            } 
          })
        },
        fail(){
          wx.showModal({
            title: '提示',
            content: '请先登录',
            success(res){
              if (res.cancel) {
                //点击取消,默认隐藏弹框
                // if (options.finish) {
                  wx.navigateBack({ 
                    delta: 1,
                    fail(){
                      wx.redirectTo({
                        url: "/pages/my/my"
                      })
                    }
                   })
                // }
              } else {
                  wx.redirectTo({
                    url: "/pages/my/my"
                  })
              }
            }
          })
        }
      })
    },
  //滑动切换
  swiperTab: function (e) {
      var that = this;
      that.setData({
          currentTab: e.detail.current
      });
  },
  //点击切换
  clickTab: function (e) {
      var that = this;
      if (this.data.currentTab === e.target.dataset.current) {
          return false;
      } else {
          that.setData({
              currentTab: e.target.dataset.current,

          })
      }
      // //  console.log(that.data.nubmerLength)
  },
  upper: function (e) {
      //  console.log(e)
  },
  lower: function (e) {
      //  console.log(e)
  },
  scroll: function (e) {
      //  console.log(e)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
  //  */
  // onShareAppMessage: function () {

  // }
})